﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace Xfs
{
    [XfsObjectSystem]
    class XfsHeartComponentAwakeSystem : XfsStartSystem<XfsHeartComponent>
    {
        public override void Start(XfsHeartComponent self)
        {
            
        }
    }

    [XfsObjectSystem]
    class XfsHeartComponentUpdateSystem : XfsUpdateSystem<XfsHeartComponent>
    {
        public override void Update(XfsHeartComponent self)
        {
            self.Heartting();
            self.Check();
        }
    }
    public static class XfsHeartComponentHelper
    {
        private static int heartTime = 0;
        private static int heartResTimer = 40000;
        public static void Heartting(this XfsHeartComponent self)
        {
            heartTime += 1;
            if (heartTime > heartResTimer)
            {
                heartTime = 0;
                if (self.IsPool) return;

                XfsSession? session = self.GetParent<XfsSession>();
                if (session == null) return;
                if (!session.IsRunning || !session.IsOuter) return;

                //Thread.Sleep(4000);
                //XfsGame.XfsSence.GetComponent<XfsTimerComponent>().WaitAsync(40000);

                C4S_Heart resqustC = new C4S_Heart() { Message = session.UserToken.Socket.RemoteEndPoint.ToString() };
                resqustC.Opcode = XfsGame.XfsSence.GetComponent<XfsOpcodeTypeComponent>().GetOpcode(resqustC.GetType());

                session.Send(resqustC);

                Console.WriteLine(XfsTimeHelper.CurrentTime() + " " + self.GetType().Name + " 53. 心跳包已发出: " + resqustC.Message);
            }
        }

        private static int checkTime = 0;
        public static void Check(this XfsHeartComponent self)
        {
            checkTime += 1;
            if (checkTime > heartResTimer)
            {
                checkTime = 0;
                if (self.IsPool) return;
                if (!self.Heartting) return;

                XfsSession? session = self.GetParent<XfsSession>();
                if (session == null) return;
                if (!session.IsOuter) return;

                //Thread.Sleep(4000);
                //XfsGame.XfsSence.GetComponent<XfsTimerComponent>().WaitAsync(40000);

                session.GetComponent<XfsHeartComponent>().CdCount += 1;
                if (session.GetComponent<XfsHeartComponent>().CdCount > session.GetComponent<XfsHeartComponent>().MaxCdCount)
                {
                    session.Close();
                }
            }
        }



    }



}
